package com.tcpengine.handler;



import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

// 消息处理类
public class TcpHandler extends ChannelInboundHandlerAdapter {
	private GameProcess gameProcess = null;
	public TcpHandler(GameProcess gameProcess) {
		this.gameProcess = gameProcess;
	}
	
	
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("有客户端连接:" + ctx.channel().remoteAddress());	   
    }
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx)throws Exception{ 
    	System.out.println(ctx.channel().remoteAddress() + "关闭连接.........");
    	
	}
	
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object obj) {
    	System.out.println("tcp网络数据到达...");
    	ByteBuf byteBuf = (ByteBuf)obj;
    	Msg msg = Encoder.decode(byteBuf);
    	if(null != msg) {
    		NetPackage netPack = new NetPackage();
    		netPack.ch = ctx.channel();
    		netPack.msg = msg;
    		netPack.netType = NetPackage.TCP_TYPE;
    		gameProcess.addPack(netPack);
    	}
    }  
   
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {	
        cause.printStackTrace();  
        ctx.close();  
    }
}
